//
//  ClientController.m
//  BufferedSocket
//
//  Created by Rainer Kupke (rkupke@gmx.de) on Thu Jul 26 2001.
//  Copyright (c) 2001 Rainer Kupke.
//

// This software is provided 'as-is', without any express or implied 
// warranty. In no event will the authors be held liable for any damages 
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose, 
// including commercial applications, and to alter it and redistribute it 
// freely, subject to the following restrictions:
//
//     1. The origin of this software must not be misrepresented; you must 
//        not claim that you wrote the original software. If you use this 
//        software in a product, an acknowledgment in the product 
//        documentation (and/or about box) would be appreciated but is not 
//        required.
//
//     2. Altered source versions must be plainly marked as such, and must
//        not be misrepresented as being the original software.
//
//     3. This notice may not be removed or altered from any source 
//        distribution.
//        

#import "ClientController.h"
#import "BufferedSocket.h"
#import "PongPrefs.h"
#import "Common.h"
#import <sys/time.h>
#import <sys/socket.h>

extern PongPrefs *sharedPongPrefs;

@implementation ClientController

-(id) init
{
    self = [super init];
	if (nil != self)
	{
		socket=nil;
	}
    return self;
}

- (void)connect
{
	LogMethod();
    socket=[[BufferedSocket alloc] initWithSocketType:SOCK_STREAM];
	NSString *hostName = [sharedPongPrefs hostName];
	int port = [sharedPongPrefs port];
	if (hostName != nil && port > 0)
	{
		NSLog(@"Connecting to host %@ on port %i", hostName, port);
		struct timeval timeout;
		// Create a timeout of two secs
	    timeout.tv_sec = 2;
	    timeout.tv_usec = 2;
	    [socket connectToHostName:hostName port:port timeout:timeout];
	}
	else
	{
		[NSException raise:SOCKET_EX_CANT_CREATE_SOCKET 
                    format:SOCKET_EX_CANT_CREATE_SOCKET];
	}
}

- (void)disconnect
{
	NSLog(@"Client controller disconnecting - releasing socket.");
	[socket release]; socket = nil;
}

- (void)send:(NSString *)msg
{   
	[socket writeString: msg];
}

- (BufferedSocket *)socket
{
	LogMethod();
	return socket;
}

- (NSString*)remoteHostName
{
	return [socket remoteHostName];
}
- (unsigned short)remotePort
{
	return [socket remotePort];
}


@end
